package ar.edu.unlp.linti.batteryconsume;

//import java.io.*;
//import java.text.SimpleDateFormat;
import java.util.*;

import android.os.*;
import android.os.PowerManager.WakeLock;
import android.app.Activity;
import android.content.*;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
//import android.graphics.Color;
//import android.graphics.Typeface;
import android.util.Log;
//import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
//import android.widget.LinearLayout;
//import android.widget.TextView;
//import android.widget.Toast;
//import android.widget.LinearLayout.LayoutParams;


public class BateryActivity extends Activity {
	public final static String TAG = "Benchmark Batery";
	//private final static String filename = "medBatery.txt";
	private WakeLock wakeLock;
	private PowerManager powerManager;
	private final Handler mHandler = new Handler();
	private Runnable mTimer1/*, mTimer2*/;
	private Intent batteryStatus;
	private IntentFilter ifilter;
	//private long startTime = (new Date()).getTime();
	private double batteryLevel = 200.0;
	private long iterations =0l;
	private String result = "";


	private void doStep() {
		LinpackLoop l = new LinpackLoop();
		l.mInfo = new Bundle();
		result = l.run_benchmark();
		iterations++;
		//this.writeResult(result + "-Bateria:" + String.valueOf(batteryLevel));
		this.readLevel();

	}

	private void readLevel() {
		int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
		int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
		double newBatteryLevel = level / (double) scale;
		//if (level >= 0 && scale > 0 && (batteryLevel > newBatteryLevel)) {
			batteryLevel = newBatteryLevel;
			/*powerManager.wakeUp(100l);*/
			persist();
			iterations=0;
			result = "";
			getAllToDos();
		//}
	}

	private void persist() {
		ContentValues values = new ContentValues();
		Long now = Long.valueOf(System.currentTimeMillis());
		values.put("sampletime", now);
		values.put("level", (int)(batteryLevel*100));
		values.put("voltage", batteryStatus.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1));//extras.getInt("voltage")
		values.put("temperature", batteryStatus.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1));
		values.put("plugged", batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1));// not charging
		values.put("iterations", iterations);// iterations
		values.put("result", result);// result
		insertBatteryData(values);
	}

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		deleteAllToDos();
		// if we were just installed and run we'll need our service started
        startService(new Intent(this, BaterySevice.class));

		/**
		Wake lock level: Ensures that the CPU is running; the screen and keyboard backlight will be allowed to go off.
		If the user presses the power button, then the screen will be turned off but the CPU will be kept on until all 
		partial wake locks have been released. 
		**/
		powerManager = (PowerManager) getSystemService(POWER_SERVICE);
		
		
		wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag");
		wakeLock.acquire();
		/********************************************************/
		//android.provider.Settings.System.putInt(getContentResolver(), android.provider.Settings.System., Settings.System.WIFI_SLEEP_POLICY_NEVER);
		
		setContentView(R.layout.activity_batery);
		ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
		batteryStatus = this.getApplicationContext().registerReceiver(null,ifilter);
		//int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
		//int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
		//batteryLevel = level / (double) scale;
		//startTime = (new Date()).getTime();

		mTimer1 = new Runnable() {
			public void run() {
				doStep();
				mHandler.postDelayed(this, 500);
			}
		};
		mHandler.postDelayed(mTimer1, 500);

		Button btn=(Button) findViewById(R.id.button1);

        btn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				startActivity(new Intent(getApplicationContext(), watts.Watts.class));
				
			}
		});  
	}

	protected void onResume() {
		super.onResume();
		mTimer1 = new Runnable() {
			public void run() {
				doStep();
				mHandler.postDelayed(this, 300);
				}
		};
		mHandler.postDelayed(mTimer1, 300);
		/*mTimer2 = new Runnable() {
			public void run() {
				readLevel();
				mHandler.postDelayed(this, 600);
			}
		};
		mHandler.postDelayed(mTimer2, 600);*/
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.batery, menu);
		return true;
	}

	protected void onPause() {
		mHandler.removeCallbacks(mTimer1);
		super.onPause();
	}
	protected void onDestroy() {
		mHandler.removeCallbacks(mTimer1);
		//mHandler.removeCallbacks(mTimer2);
		wakeLock.release();
		super.onDestroy();
	}

	/*private boolean writeResult(String output) {
		File writeDir = new File(Environment.getExternalStorageDirectory()
				.getPath());
		if (!writeDir.exists()) {
			writeDir.mkdirs();
		}

		File file = new File(writeDir, filename);
		try {
			if (!file.exists()) {
				file.createNewFile();
			}
			FileWriter fw = new FileWriter(file);
			Calendar c = Calendar.getInstance();
			String formattedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(c.getTime());

			String timeTransc = "";
			long delta = (new Date()).getTime() - startTime;
			double diffSecs = delta / 1000;
			if (diffSecs > 60) {
				timeTransc = (diffSecs / 60) + " mins";

			}
			if (diffSecs > (60 * 60)) {
				timeTransc = (diffSecs / (60 * 60)) + " horas";
			}

			//Toast.makeText(getApplicationContext(),
			//		formattedDate + " - " + timeTransc + " - " + output,
			//		Toast.LENGTH_SHORT).show(); 
			fw.append(formattedDate + " - " + timeTransc + " - " + output);
			fw.flush();
			fw.close();
			Log.w(TAG, "File data  :" + output);
		} catch (Exception e) {
			Log.i(TAG, "Write Failed.");
			e.printStackTrace();
			return false;
		}
		return true;
	}*/
	
	public boolean insertBatteryData(ContentValues values) {
		DatabaseHelper mOpenHelper = null;
		SQLiteDatabase db = null;
		boolean rc = true;
		try {
			mOpenHelper = new DatabaseHelper(this);
			db = mOpenHelper.getWritableDatabase();
			Long rowid = db.insert(DatabaseHelper.LEVELS_TABLE, null, values);
			//Log.e(TAG, "database insert: " + values);
			if (rowid < 0) {
				Log.w(TAG, "database insert failed: " + rowid);
				rc = false;
			}
		} catch (Exception e) {
			Log.e(TAG, "database exception");
			rc = false;
		}
		if (db != null) db.close();
		if (mOpenHelper != null) mOpenHelper.close();
		return rc;
	}
	
	/*
	 * getting all todos
	 * */
	public List<Integer> getAllToDos() {
	    List<Integer> todos = new ArrayList<Integer>();
	    String selectQuery = "SELECT  * FROM " + DatabaseHelper.LEVELS_TABLE;
	 
	    //Log.i(DatabaseHelper.LEVELS_TABLE, selectQuery);
	 
	    SQLiteDatabase db = (new DatabaseHelper(this)).getReadableDatabase();
	    Cursor c = db.rawQuery(selectQuery, null);
	    
	    Log.e(TAG, "numbers of rows in the cursor " + c.getCount()); 
	 
	    // looping through all rows and adding to list
	    /*if (c.moveToFirst()) {
	        do {
	            // adding to todo list
	            todos.add(c.getInt((c.getColumnIndex("level"))));
	            Log.i(DatabaseHelper.LEVELS_TABLE, "level:"+c.getInt((c.getColumnIndex("level"))));
	        } while (c.moveToNext());
	    }*/
	 
	    return todos;
	}
	
	/*
	 * delete all todos
	 * */
	public void deleteAllToDos() {
	    //String selectQuery = "Delete  * FROM " + DatabaseHelper.LEVELS_TABLE;
	    SQLiteDatabase db = (new DatabaseHelper(this)).getWritableDatabase();
	    //Cursor c = db.rawQuery(selectQuery, null);
	    db.delete(DatabaseHelper.LEVELS_TABLE, null, null);
	    Log.e(TAG, "Deleted all numbers of rows in the cursor "); 

	}

}
